package com.example.flutter_flutter_api;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.baidu.mapapi.map.MapView;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.GeneratedPluginRegistrant2;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "com.example.flutter_flutter_api/battery";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(),CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
                if(call.method.equals("getBatteryLevel"))
                {
                    gotoSecond();
                    int batteryLevel = getBatteryLevel();
                    if(batteryLevel != -1)
                        result.success(batteryLevel);
                    else
                        result.error("UNAVALIABLE","Battery level not available.",null);
                }
                else
                {
                    result.notImplemented();
                }

            }
        });
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        MapView mapView = new MapView(this);
        GeneratedPluginRegistrant2.registerWith(flutterEngine, mapView);
    }

    public void gotoSecond()
    {
        Intent i = new Intent(MainActivity.this,SecondActivity.class);
        startActivity(i);
    }
    //调用原生层API获取系统电池电量
    private int getBatteryLevel() {
        int batteryLevel = -1;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            BatteryManager batteryManager =
                    (BatteryManager) this.getSystemService(this.BATTERY_SERVICE);
            batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } else {
            Intent intent =
                    new ContextWrapper(this)
                            .registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            batteryLevel =
                    (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100)
                            / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        }

        return batteryLevel;
    }
}
